package com.achun.getcouponleague.presenter.impl;

import com.achun.getcouponleague.Bean.Histories;
import com.achun.getcouponleague.Bean.SearchRecommend;
import com.achun.getcouponleague.Bean.SearchResult;
import com.achun.getcouponleague.model.ServiceApi;
import com.achun.getcouponleague.presenter.ISearchPresenter;
import com.achun.getcouponleague.utils.LocalHistoryUtil;
import com.achun.getcouponleague.utils.Logutils;
import com.achun.getcouponleague.utils.RetrogitManager;
import com.achun.getcouponleague.view.ISearchCallBack;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class SearchPresenter implements ISearchPresenter {

    private final ServiceApi serviceApi;
    private LocalHistoryUtil localHistoryUtil=LocalHistoryUtil.getInstance();
    private ISearchCallBack iSearchCallBack;
    private int CurrentPage=1;
    private String currentkeyword;

    public SearchPresenter(){
        Retrofit retrofit = RetrogitManager.getInstance().getRetrofit();
        serviceApi = retrofit.create(ServiceApi.class);
    }
    public static final String LOCAL_SEARCH_CACHE_KEY="LOCAL_SEARCH_CACHE_KEY";
    public static final int DEFAULT_HISTORIES_SIZE=10;
    private int historiesMaxSize=DEFAULT_HISTORIES_SIZE;
    //添加历史记录
    private void saveHistory(String history){
        Histories histories = localHistoryUtil.getValue(LOCAL_SEARCH_CACHE_KEY,Histories.class);
        //如果说已经存在的，就干掉，然后再添加
        List<String> historiesList=null;
        if (histories!=null&&histories.getHistories()!=null) {
           historiesList = histories.getHistories();
            if (historiesList.contains(history)){
                historiesList.remove(history);
            }
        }
        //去重完成
        //处理没有数据的情况
        if (historiesList == null) {
            historiesList=new ArrayList<>();
        }
        if (histories == null) {
            histories=new Histories();
        }
        //对个数进行限制
        if (historiesList.size()>historiesMaxSize){
            historiesList=historiesList.subList(0,historiesMaxSize);
        }
        //添加记录
        historiesList.add(history);
        histories.setHistories(historiesList);
        localHistoryUtil.saveCache(LOCAL_SEARCH_CACHE_KEY,histories);
    }
    @Override
    public void registerCallback(ISearchCallBack callback) {
        this.iSearchCallBack=callback;
    }

    @Override
    public void unRegisterCallback(ISearchCallBack callback) {
        if (iSearchCallBack != null) {
            this.iSearchCallBack=null;
        }
    }
//加载历史搜索记录
    @Override
    public void getHisgory() {
        Histories cachehistory = localHistoryUtil.getValue(LOCAL_SEARCH_CACHE_KEY, Histories.class);
        if (cachehistory==null||cachehistory.getHistories()==null){
            if (iSearchCallBack != null) {
                iSearchCallBack.onLoadHisgroy(null);
            }
            return;
        }else {
            List<String> histories = cachehistory.getHistories();
            iSearchCallBack.onLoadHisgroy(histories);
        }
    }

    @Override
    public void deleteHisgory() {
        localHistoryUtil.deleteCache(LOCAL_SEARCH_CACHE_KEY);
    }

    @Override
    public void doSearch(String keyword) {
        if (iSearchCallBack != null) {
            iSearchCallBack.onLoading();
        }
        this.currentkeyword=keyword;
        //保存搜索记录
        saveHistory(keyword);
        CurrentPage=1;
        Call<SearchResult> task = serviceApi.getSearchResult(CurrentPage, keyword);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code = response.code();
                if (code== HttpURLConnection.HTTP_OK){
                    //加载成功
                    CurrentPage++;
                    SearchResult searchResult = response.body();
                    handleOnSuccess(searchResult);
                }else {
//                    网络错误
                    handleOnError();
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
//                    网络错误
                handleOnError();
            }
        });
    }

    private void handleOnError() {
        if (iSearchCallBack != null) {
            iSearchCallBack.onError();
        }
    }

    private void handleOnSuccess(SearchResult searchResult) {
        if (iSearchCallBack != null) {
            try {

                if (searchResult.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data().size()!=0){
                    //不为空
                    iSearchCallBack.onLoadSearchResult(searchResult);
                }else {
                    //为空
                    iSearchCallBack.onEmpty();
                }
            }catch (Exception e){
                //为空
                iSearchCallBack.onEmpty();
            }
        }

    }

    @Override
    public void reSearch() {
        Call<SearchResult> task = serviceApi.getSearchResult(CurrentPage, currentkeyword);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code = response.code();
                if (code== HttpURLConnection.HTTP_OK){
                    //加载成功
                    CurrentPage++;
                    SearchResult searchResult = response.body();
                    handleOnSuccess(searchResult);
                }else {
//                    网络错误
                    handleOnError();
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
//                    网络错误
                handleOnError();
            }
        });
    }

    @Override
    public void loadedMore() {
        Call<SearchResult> task = serviceApi.getSearchResult(CurrentPage, currentkeyword);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code = response.code();
                if (code== HttpURLConnection.HTTP_OK){
                    //加载成功
                    CurrentPage++;
                    SearchResult searchResult = response.body();
                    handleMoreOnSuccess(searchResult);
                }else {
//                    网络错误
                    if (iSearchCallBack != null) {
                        iSearchCallBack.onLoadMoreError();
                    }
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
//                    网络错误
                if (iSearchCallBack != null) {
                    iSearchCallBack.onLoadMoreError();
                }
            }
        });
    }

    private void handleMoreOnSuccess(SearchResult searchResult) {
        if (iSearchCallBack != null) {
            try {

                if (searchResult.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data().size()!=0){
                    //不为空
                    iSearchCallBack.onLoadMoreResult(searchResult);
                }else {
                    //为空
                    iSearchCallBack.onLoadMoreEmpty();
                }
            }catch (Exception e){
                //为空
                iSearchCallBack.onLoadMoreEmpty();
            }
        }
    }

    @Override
    public void getRecommendWords() {
        Call<SearchRecommend> task = serviceApi.getSearchRecommend();
        task.enqueue(new Callback<SearchRecommend>() {
            @Override
            public void onResponse(Call<SearchRecommend> call, Response<SearchRecommend> response) {
                int code = response.code();
                SearchRecommend searchRecommend = response.body();
                Logutils.e(this.getClass(),"推荐词--》"+searchRecommend);
                if (iSearchCallBack != null) {
                    if (code == HttpURLConnection.HTTP_OK) {
                            iSearchCallBack.onLoadRecommend(searchRecommend);
                    }
                }
            }

            @Override
            public void onFailure(Call<SearchRecommend> call, Throwable t) {
                Logutils.e(this.getClass(),"推荐词错误--》"+t.toString());
            }
        });
    }
}
